package nl.boelen.game.client.connection;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
import nl.boelen.game.utils.Utils;

public class ClientTCPReceiver extends Thread {

    private ServerSocket socket;
    private ClientPacketHandler packetHandler;

    public ClientTCPReceiver(ClientPacketHandler packetHandler) {
        this.packetHandler = packetHandler;
        while (true) {
            int port = new Random().nextInt(9999);
            try {
                this.socket = new ServerSocket(new Random().nextInt(15000) + 5000);

            } catch (BindException be) {
                Utils.LOG("Port " + port + " in use, try other port");
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (socket != null) {
                break;
            }
        }
    }

    public void run() {
        String message = "";

        while (true) {
            try (Socket server = socket.accept();) {
                try (DataInputStream in = new DataInputStream(server.getInputStream())) {
                    try (DataOutputStream out = new DataOutputStream(server.getOutputStream())) {

                        InetAddress address = server.getInetAddress();
                        int port = server.getPort();
                        int size = in.readInt();
                        byte[] data = new byte[size];

                        if (size > 0) {
                            in.readFully(data);

                            message = "OK";
                            out.writeInt(message.length());
                            out.write(message.getBytes());
                            out.flush();
                            
                            packetHandler.parsePacket(data, address, port);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public int getPort() {
        return socket.getLocalPort();
    }
}
